$(function(){
	$('input.x-i-search').focus(function(){
		$(this).parent('.x-wrap').css('border-color','#7eabd6');
	}).blur(function(){
		$(this).parent('.x-wrap').css('border-color','#dedede');
	});
	
	//滚动条 slim-scroll
	$('.slim-scroll').each(function(){
		var $self = $(this), $data = $self.data(), $slimResize;
		$self.slimScroll($data);
		$(window).resize(function(e) {
			clearTimeout($slimResize);
			$slimResize = setTimeout(function(){$self.slimScroll($data);}, 500);
		});
	    $(document).on('updateNav', function(){
	      $self.slimScroll($data);
	    });
	});	
	
	// dropdown menu
    $.fn.dropdown.Constructor.prototype.change = function(e){
      e.preventDefault();
      var $item = $(e.target), $select, $checked = false, $menu, $label;
      !$item.is('a') && ($item = $item.closest('a'));
      $menu = $item.closest('.dropdown-menu');
      $label = $menu.parent().find('.dropdown-label');
      $labelHolder = $label.text();
      $select = $item.parent().find('input');
      $checked = $select.is(':checked');
      if($select.is(':disabled')) return;
      if($select.attr('type') == 'radio' && $checked) return;
      if($select.attr('type') == 'radio') $menu.find('li').removeClass('active');
      $item.parent().removeClass('active');
      !$checked && $item.parent().addClass('active');
      $select.prop("checked", !$select.prop("checked"));

      $items = $menu.find('li > input:checked');
      if ($items.length) {
          $text = [];
          $items.each(function () {
              var $str = $(this).parent().text();
              $str && $text.push($.trim($str));
          });

          $text = $text.length < 4 ? $text.join(', ') : $text.length + ' selected';
          $label.html($text);
      }else{
        $label.html($label.data('placeholder'));
      }
    }
    $(document).on('click.dropdown-menu', '.dropdown-select > li > a', $.fn.dropdown.Constructor.prototype.change);

  	// tooltip
    $("[data-toggle=tooltip]").tooltip();
    
    
  //页面不相干的元素点击后隐藏消息侧栏
	$(document).on('mousedown',function(event){

		//不在编辑区域，不是点击区块的修改按钮
		if($('#container').hasClass('aside-in')
				&& $(event.target).parents('#aside-container').length == 0
				&& $(event.target).parents('#navbar').length == 0){
			//$.niftyAside('hide');
			$('#container').removeClass('aside-in');
		}
		//$(event.target).trigger('mousedown');
		//return true;
		//console.info(event);
	});
	//删除页面加载的遮罩
	toast.hideloading();
})

/**
 * 操纵toastor的便捷类
 * @type {{success: success, error: error, info: info, warning: warning}}
 */
var toast = {
    /**
     * 成功提示
     * @param text 内容
     * @param title 标题
     */
    success: function (text, title) {
        toastr.options = {
            "closeButton": true,
            "debug": false,
  		  	"progressBar": true,
            "positionClass": "toast-top-right",
            "onclick": null,
            "showDuration": "1000",
            "hideDuration": "1000",
            "timeOut": "7000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
        }
        toastr.success(text, title);
    },
    /**
     * 失败提示
     * @param text 内容
     * @param title 标题
     */
    error: function (text, title) {
        toastr.options = {
            "closeButton": true,
            "debug": false,
  		  	"progressBar": true,
            "positionClass": "toast-top-right",
            "onclick": null,
            "showDuration": "1000",
            "hideDuration": "1000",
            "timeOut": "7000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
        }
        toastr.error(text, title);
    },
    /**
     * 信息提示
     * @param text 内容
     * @param title 标题
     */
    info: function (text, title) {
        toastr.options = {
            "closeButton": false,
            "debug": false,
  		  	"progressBar": true,
            "positionClass": "toast-top-right",
            "onclick": null,
            "showDuration": "1000",
            "hideDuration": "1000",
            "timeOut": "7000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
        }
        toastr.info(text, title);
    },
    /**
     * 警告提示
     * @param text 内容
     * @param title 标题
     */
    warning: function (text, title) {
        toastr.options = {
            "closeButton": false,
            "debug": false,
  		  	"progressBar": true,
            "positionClass": "toast-top-right",
            "onclick": null,
            "showDuration": "1000",
            "hideDuration": "1000",
            "timeOut": "7000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
        }
        toastr.warning(text, title);
    },
    loading:function(){
    	$('body').append("<div id='submit_loading' class='purchase-loading'><div class='loading-cont'></div></div>");
    },
    hideloading:function(){
    	$(".purchase-loading").removeClass('fadeIn').fadeOut(600,function(){
    		$(".purchase-loading").remove();
    	});
    },
    hide:function(){
    	toastr.clear();
    	//$("#submit_loading").remove();
    }
}


/**
 * 处理ajax返回结果
 */
function handleAjax(a,fun) {
    //如果需要跳转的话，消息的末尾附上即将跳转字样
    if (a.url) {
        a.info += '，页面即将跳转～';
    }

    //弹出提示消息
    if (a.status) {
        toast.success(a.info, '温馨提示');
    } else {
        toast.error(a.info, '温馨提示');
    }
    
    if(typeof(fun) == 'function'){
    	fun();
    }

    //需要跳转的话就跳转
    var interval = 1500;
    if (a.url == "refresh") {
        setTimeout(function () {
            location.href = location.href;
        }, interval);
    } else if (a.url) {
        setTimeout(function () {
            location.href = a.url;
        }, interval);
    }
}  


//重组组织机构tree数据
var resourceTreeData = function(data){
    if(!data || data.length == 0){
        return [];
    }
    //console.info(data);
    //最终数据
    var finalData = [];
    //查询子集，循环方法
    var getChildren = function(arr,pid){
        var childArr = [];
        //预存数组长度，节省遍历时间
        var blen = arr.length;
        for(var i = 0;i < blen;i++){
            var vo = arr[i];
            //去掉第一级，非当前内容子集
            if(!vo.parentId || vo.parentId != pid){
                continue;
            }
            var info = vo;
            //循环遍历，查找无限层级
            var children = getChildren(data,vo.menuId);
            //存在子集，保存
            if(children) info.children = children;
            childArr.push(info);
        }
        return childArr;
    }

    //查找第一级，查找对应子集
    var slen = data.length;//预存数组长度，节省遍历时间
    for(var a = 0;a < slen;a++){
    	//console.info(data[a].parentId);
        //只收第一级内容
        if(data[a].parentId == 0){
            var info = data[a];
            var children = getChildren(data,data[a].menuId);
            if(children) info.children = children;
            finalData.push(info);
        }
    }

    return finalData;
};
//初始化菜单
var init_menutree = function(){
	var curl = parse_url(location.href);
	//var roleCode = getCookie('roleCode');

	if(curl.path.indexOf('newIndex') > 0){
    	$('#mainnav-menu li:eq(0)').addClass('active-link');
	}
	$.ajax({
        type: 'get', 
//        url: 'static/plugin/bootstrap-table/staticData/menu.json',
        url: path+'/getMenus',
        dataType:'json',
        success: function(data) { 
        	if(!data || !data.length) return false;
			var nda = resourceTreeData(data);
            //console.info(nda);
			var hl = '';
			$.each(nda,function(index,vo){
				// 第一级
                hl += '<li class="list-divider"></li><li class="list-header">'+vo.title+'</li>';
                var children_first = vo.children;
                var cflen = children_first.length;
                if(cflen){
                	var child_html = function(children){
                		var chtml = '';
                        $.each(children,function(fdx,fvo){

                            var url = path+fvo.url;
                            if(!fvo.url || fvo.url == '#') url = '#';

                          
                          
                            var clas = curl.path == path+fvo.url ? ' class="active-link"' : '';
                            var shtml = '',arrow='';
                            //存在子集
                            if(fvo.children.length){
                                arrow = '<i class="arrow"></i>';
                            	url = 'javascript:void(0);';
                                shtml = '<ul class="collapse" aria-expanded="false">'+child_html(fvo.children)+'</ul>';
							}

                            chtml += '<li'+clas+'><a href="'+url+'">'+
                                '<i class="'+fvo.iconClass+'"></i> <span class="menu-title">'+fvo.title+'</span>'+
                                arrow+
                                '</a>'+shtml+
								'</li>';
                        });
                        return chtml;
					}
                    hl += child_html(children_first);

				}

			});
			$('#mainnav-menu').append(hl);

			$.niftyNav("bind");
		}
    })
	
}

if (self == top) {
    //页面数据初始化
	init_menutree();
}
//收放左侧菜单
$(".mainnav-toggle").click(function(){
	 if($('#container').hasClass("mainnav-lg")){
		 $('#container').removeClass("mainnav-lg");
		 $('#container').addClass("mainnav-sm");
	 }else if($('#container').hasClass("mainnav-sm")){
		 $('#container').removeClass("mainnav-sm");
		 $('#container').addClass("mainnav-lg");
	 }
	});
//设置ajax默认的complete函数和error函数，当后端返回响应码是500及以上的，就会进入error函数执行
$.ajaxSetup({
	beforeSend:function(xmlHttp){
//		xmlHttp.setRequestHeader("If-Modified-Since","0");
//        xmlHttp.setRequestHeader("Cache-Control","no-cache");
		//请求之前 显示加载提示
		if($(".purchase-loading").length == 0) toast.loading();
	},
    complete: function (jqXHR) {
    	//请求结束之后调用
    	toast.hideloading();
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
//        console.log(XMLHttpRequest.responseJSON);
        if (XMLHttpRequest.status == 501) {
            //ajax请求
            result = JSON.parse(XMLHttpRequest.responseText);
            toast.error(result.message + '！','失败提示'); 
        } else if(XMLHttpRequest.status == 500) {
            //status=501
            //页面跳转请求
            location =path + "/static/500.jsp";
        }else{
        	toast.error( '未知异常！','失败提示'); 
        }
    }
});



